<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <!-- 主表单区域 -->
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row   >
          <a-col :span="8" >
            <a-form-model-item label="单据编号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="code">
              <a-input v-model="model.code" disabled placeholder="请输入单据编号" ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8" >
            <a-form-model-item label="仓库编号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="warehouseCode">
              <j-dict-select-tag style="width: 200px" type="list" v-model="model.warehouseCode"
                                 dictCode="erp_warehouse,name,code" placeholder="请选择仓库编号" @change="handlerChange"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="8" >
            <a-form-model-item label="盘点类型" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="inventoryType">
              <j-dict-select-tag style="width: 200px" type="list" v-model="model.inventoryType"
                                 dictCode="inventory_type" placeholder="请选择盘点类型" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8" >
            <a-form-model-item label="盘点年月" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="inventoryMonth">
              <a-month-picker v-model="model.inventoryMonth" placeholder="盘点年月" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8" >
            <a-form-model-item label="制单人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="inventoryMonth">
              <a-input v-model="model.createBy" disabled placeholder="请输入制单人" ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8" >
            <a-form-model-item label="制单日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="inventoryMonth">
              <a-input v-model="model.createTime" disabled placeholder="请输入制单日期" ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8" >
            <a-form-model-item label="备注" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="remark">
              <a-input v-model="model.remark" placeholder="请输入备注" ></a-input>
            </a-form-model-item>
          </a-col>
        </a-row>
<!--        <a-row type="flex" justify="end" align="top" class="custom-row">-->
<!--          <a-col :span="24" :pull="4">-->
<!--            <a-form-model-item label="备注" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="remark">-->
<!--              <a-input v-model="model.remark" placeholder="请输入备注" ></a-input>-->
<!--            </a-form-model-item>-->
<!--          </a-col>-->
<!--        </a-row>-->
      </a-form-model>
    </j-form-container>
      <!-- 子表单区域 -->
    <a-tabs v-model="activeKey" @change="handleChangeTabs">
      <a-tab-pane tab="盘点明细" :key="refKeys[0]" :forceRender="true">
        <j-vxe-table
          keep-source
          :ref="refKeys[0]"
          :loading="bussWarehouseInventoryDetailTable.loading"
          :columns="bussWarehouseInventoryDetailTable.columns"
          :dataSource="bussWarehouseInventoryDetailTable.dataSource"
          :maxHeight="300"
          :disabled="formDisabled"
          :rowNumber="true"
          :rowSelection="true"
          :toolbar="true"
          @edit-closed="editMaterialClosedEvent"
          :toolbarConfig="{slot: ['prefix', 'suffix'], btn: ['clearSelection']}"
          />
      </a-tab-pane>
    </a-tabs>
  </a-spin>
</template>

<script>

import { getAction, putAction } from '@/api/manage'
  import { JVxeTableModelMixin } from '@/mixins/JVxeTableModelMixin.js'
  import { JVXETypes } from '@/components/jeecg/JVxeTable'
  import { getRefPromise,VALIDATE_FAILED} from '@/components/jeecg/JVxeTable/utils/vxeUtils.js'
  import { validateDuplicateValue } from '@/utils/util'
  import JFormContainer from '@/components/jeecg/JFormContainer'
  import moment from 'dayjs'
  import Vue from 'vue'
  import { USER_INFO } from '@/store/mutation-types'

  export default {
    name: 'BussWarehouseInventoryForm',
    mixins: [JVxeTableModelMixin],
    components: {
      JFormContainer,
    },
    data() {
      return {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        moment,
        model:{
         },
        // 新增时子表默认添加几行空数据
        addDefaultRowNum: 1,
        validatorRules: {
          warehouseCode: [{required: true, message: '请选择仓库编号'}],
          inventoryType: [{required: true, message: '请选择盘点类型'}],
        },
        refKeys: ['bussWarehouseInventoryDetail', ],
        tableKeys:['bussWarehouseInventoryDetail', ],
        activeKey: 'bussWarehouseInventoryDetail',
        // 盘点明细
        bussWarehouseInventoryDetailTable: {
          loading: false,
          dataSource: [],
          columns: [
            {
              title: '物料id',
              key: 'materialId',
              type: JVXETypes.hidden,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '行项目',
              key: 'rowNum',
              type: JVXETypes.hidden,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '物料分类',
              key: 'classificationId_dictText',
              type: JVXETypes.normal,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '物料编号',
              key: 'materialCode',
              type: JVXETypes.normal,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '物料名称',
              key: 'materialName',
              type: JVXETypes.normal,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '规格型号',
              key: 'noneSpec',
              type: JVXETypes.normal,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '主计量',
              key: 'meUnit_dictText',
              type: JVXETypes.normal,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '库存数量',
              key: 'quantity',
              type: JVXETypes.normal,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '盘点数量',
              key: 'inventoryQuantity',
              type: JVXETypes.input,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '盈亏数量',
              key: 'breakevenQuantity',
              type: JVXETypes.normal,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '辅助单位',
              key: 'abc',
              type: JVXETypes.normal,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '辅助库存数量',
              key: 'e',
              type: JVXETypes.normal,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '盈亏辅助数量',
              key: 'f',
              type: JVXETypes.normal,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '备注',
              key: 'remark',
              type: JVXETypes.input,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '是否关闭',
              key: 'isClose',
              type: JVXETypes.normal,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            // {
            //   title: '盘点表id',
            //   key: 'mainId',
            //    type: JVXETypes.input,
            //   width:"200px",
            //   placeholder: '请输入${title}',
            //   defaultValue:'',
            // },
          ]
        },
        inventoryDetailTable:'',
        url: {
          add: "/business/bussWarehouseInventory/add",
          edit: "/business/bussWarehouseInventory/edit",
          queryById: "/business/bussWarehouseInventory/queryById",
          bussWarehouseInventoryDetail: {
            list: '/business/bussWarehouseInventory/queryBussWarehouseInventoryDetailByMainId'
          },
          list: "/detail/bussInventoryDetails/getkc"
        }
      }
    },
    props: {
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      }
    },
    computed: {
      formDisabled(){
        return this.disabled
      },
    },
    created () {
      let user = Vue.ls.get(USER_INFO)
      this.model.createTime = moment().format("YYYY-MM-DD HH:mm:ss")
      this.model.createBy = user.username
    },
    watch:{
      // 'model.warehouseCode'(newName, oldName) {
      //   // console.log('User name changed from', oldName, 'to', newName);
      //   this.loadDataed();
      // },
    },
    mounted() {
      this.$nextTick(() => {
        this.getAllTable().then(tables=>{
          this.inventoryDetailTable = tables[0]
        })
        setTimeout(() => {
          if(!this.model.id){
            let rows = this.inventoryDetailTable.getNewDataWithId()
            this.inventoryDetailTable.removeRowsById(rows[0].id)
          }
          this.inventoryDetailTable.resetScrollTop();
        },500)
      })
    },
    methods: {
      getSequenceNum() {
        let url = "/sys/fillRule/executeRuleByCode/pdd";
        putAction(url, {}).then(res => {
          // 执行成功，获取返回的值，并赋到页面上
          if (res.success) {
            this.model.code = res.result;
          }
        })
      },
      addBefore(){
        this.bussWarehouseInventoryDetailTable.dataSource=[]
        this.getSequenceNum()
      },
      getAllTable() {
        let values = this.tableKeys.map(key => getRefPromise(this, key))
        return Promise.all(values)
      },
      handlerChange(){
        let params = { warehouseCode: this.model.warehouseCode }
        this.requestSubTableData(this.url.list, params, this.bussWarehouseInventoryDetailTable,()=>{
          this.bussWarehouseInventoryDetailTable.dataSource.forEach((item,index)=>{
            item.rowNum = index
          })
        })
      },
      loadDataed(){

      },
      editMaterialClosedEvent({ row, column }){
        let xTable = this.$refs.bussWarehouseInventoryDetail
        let field = column.property
        let cellValue = row[field]
        let _this = this
        this.$nextTick(() => {
          if('inventoryQuantity' === field){
            this.bussWarehouseInventoryDetailTable.dataSource.forEach((item,index)=>{
              if(item.rowNum === row.rowNum){
                item.breakevenQuantity =  item.inventoryQuantity - item.quantity
              }
            })
            // console.log(this.bussWarehouseInventoryDetailTable.dataSource)
            // this.xTable.resetScrollTop();
          }
        })
      },
      /** 调用完edit()方法之后会自动调用此方法 */
      editAfter() {
        this.$nextTick(() => {
        })
        // 加载子表数据
        if (this.model.id) {
          let params = { id: this.model.id }
          this.requestSubTableData(this.url.bussWarehouseInventoryDetail.list, params, this.bussWarehouseInventoryDetailTable,)
        }
      },
      //校验所有一对一子表表单
        validateSubForm(allValues){
            if(allValues.tablesValue[0].tableData.length == 0){
              this.$message.error('请添加盘点信息！')
              return false;
            }
            return new Promise((resolve,reject)=>{
              Promise.all([
              ]).then(() => {
                resolve(allValues)
              }).catch(e => {
                if (e.error === VALIDATE_FAILED) {
                  // 如果有未通过表单验证的子表，就自动跳转到它所在的tab
                  this.activeKey = e.index == null ? this.activeKey : this.refKeys[e.index]
                } else {
                  console.error(e)
                }
              })
            })
        },
      /** 整理成formData */
      classifyIntoFormData(allValues) {
        let _this = this;
        let main = Object.assign(this.model, allValues.formValue)
        return {
          ...main, // 展开
          bussWarehouseInventoryDetailList: _this.processingData(allValues.tablesValue[0].tableData),
        }
      },
      validateError(msg){
        this.$message.error(msg)
      },
      processingData(data){
        let newJsonArray = data.map(item => {
          return { ...item, id: item.id && item.id.indexOf('row') >= 0 ? '' : item.id  };
        });
        return newJsonArray;
      },

    }
  }
</script>

<style scoped>
.custom-row{
  display: flex;
  justify-content: start; /* Ensure content aligns to the end (right) */
}
</style>